/**
 * 高德地图逻辑组件
 */
import React from 'react';
import { Input, AutoComplete, Spin, Row } from 'antd';
import { Map as GDMap, Marker } from 'react-amap';
import { AMAP_KEY } from '../config';

const Map = ({ defaultPosition, onChange, onSelect, visible }) => {
    const [searchValue, setSearchValue] = React.useState('');
    const [searchList, setSearchList] = React.useState([]);
    const [currentPosition, setCurrentPosition] = React.useState(defaultPosition);
    const [mapMounted, setMapMounted] = React.useState(false);

    const mapRef = React.useRef(null);
    const placeSearchRef = React.useRef(null);
    const geocoderRef = React.useRef(null);

    // 高德地图事件
    const events = {
        created: async map => {
            const { AMap } = window;
            mapRef.current = map;

            // 安装高德地址转换插件
            await AMap.plugin('AMap.Geocoder', () => {
                geocoderRef.current = new AMap.Geocoder({ city: '010' });
            });

            // 安装高德地址搜索插件
            await AMap.plugin('AMap.PlaceSearch', () => {
                placeSearchRef.current = new window.AMap.PlaceSearch();
            });

            setMapMounted(true);
        },
        click: map => {
            const { lnglat = {} } = map;
            setCurrentPosition(lnglat);
        }
    };

    const handleSearch = _value => {
        if (!_value) {
            setSearchList([]);
        }
        placeSearchRef.current.search(_value, (status, result) => {
            const { info, poiList = {} } = result;
            if (info === 'OK') {
                const { pois = [] } = poiList;
                const finalList = pois.map(item => (
                    <AutoComplete.Option key={item.id} data={item}>
                        {item.name}
                    </AutoComplete.Option>
                ));
                setSearchList(finalList);
            }
        });
        setSearchValue(_value);
    };

    const handleSelect = (_, option) => {
        const { props = {} } = option;
        const { data = {} } = props;
        setCurrentPosition(data.location);
        setSearchValue(data.name);
        onSelect(data.name);
    };

    React.useEffect(() => {
        if (!visible) {
            setSearchValue('');
        }
    }, [visible]);

    // 将地址位置信息转为实际地址信息
    React.useEffect(() => {
        if (!geocoderRef.current || !mapMounted || !currentPosition) {
            return;
        }
        geocoderRef.current.getAddress([currentPosition.lng, currentPosition.lat], (status, result) => {
            const { info, regeocode = {} } = result;
            if (info === 'OK') {
                const { formattedAddress } = regeocode;
                onChange({ currentPosition, formattedAddress });
            }
        });
    }, [currentPosition, mapMounted]);

    const loadingComponent = (
        <Row type="flex" justify="center" align="middle" style={{ height: '100%' }}>
            <Spin />
        </Row>
    );

    return (
        <GDMap
            amapkey={AMAP_KEY}
            events={events}
            center={currentPosition}
            loading={loadingComponent}
            plugins={['ToolBar']}
        >
            <div style={{ position: 'absolute', top: 20, left: 20 }}>
                <AutoComplete
                    value={searchValue}
                    dataSource={searchList}
                    onChange={handleSearch}
                    onSelect={handleSelect}
                    optionLabelProp="label"
                >
                    <Input value={searchValue} addonBefore="请输入关键字" style={{ width: 400 }} allowClear />
                </AutoComplete>
            </div>
            {currentPosition && <Marker position={currentPosition} />}
        </GDMap>
    );
};

export default Map;
